package sample.Koans

import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
import java.util.Calendar

/**
 * Created by runjia on 17-6-1.
 */
// delegates pattern to implements lazy init
class LazyProperty2(val initializer: () -> Int) {
    val lazyValue: Int by lazy(initializer)
}

class LazyProperty3(val initializer: (StringBuilder) -> Int) {
}

class D {
    var date: MyDate by EffectiveDate()

    var lazy2 = LazyProperty2( { "abc".length } )

    var lazy3 = LazyProperty3({ it.capacity() })
}

class EffectiveDate<in R> : ReadWriteProperty<R, MyDate> {

    var timeInMillis: Long? = null

    override fun getValue(thisRef: R, property: KProperty<*>): MyDate = timeInMillis!!.toDate()

    override fun setValue(thisRef: R, property: KProperty<*>, value: MyDate) {
        timeInMillis = value.toMillis()
    }
}

fun MyDate.toMillis(): Long {
    val c = Calendar.getInstance()
    c.set(year, month, dayOfMonth, 0, 0, 0)
    c.set(Calendar.MILLISECOND, 0)
    return c.getTimeInMillis()
}

fun Long.toDate(): MyDate {
    val c = Calendar.getInstance()
    c.setTimeInMillis(this)
    return MyDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE))
}